import os
from utils import doc_util, date_util, read_config

base_path = os.path.join(os.getcwd().split('StockMonitor')[0] + 'StockMonitor')
mark_path = os.path.join(read_config.data_path, 'webs', 'mark', 'project')


def record_pid(p_name):
    if base_path[0] == '/':  # 使用linux系统 还没写
        return 1
    if os.path.exists(os.path.join(mark_path, 'flag')):
        return 0
    doc_util.gen_new_doc(mark_path, 'flag', ['锁占用'])
    pid_dict = doc_util.get_a_doc_dict(os.path.join(mark_path, 'project'), 'pid')
    task_pid_list = []
    commend = 'tasklist|findstr python '
    r = os.popen(commend)
    while 1:
        rr = r.read()
        if rr == '':
            break
        task_list = rr.split('\n')
        for task in task_list:
            if len(task) < 3:
                continue
            r_list = task.replace('   ', '').replace('  ', ' ').split(' ')
            task_pid_list.append(r_list[1])
    # 删除重复的
    del_pid = []
    for pid in pid_dict.keys():
        pid_info = pid_dict[pid]
        if pid_info['name'] == p_name:
            del_pid.append(pid)
    for d_pid in del_pid:
        pid_dict.pop(d_pid)
    for task_pid in task_pid_list:
        if task_pid not in pid_dict.keys():
            pid_dict[task_pid] = {'pid': task_pid, 'timestamp': date_util.get_timestamp_now(), 'name': p_name}
    doc_util.gen_a_doc(mark_path, 'project', pid_dict)
    doc_util.del_doc(os.path.join(mark_path, 'flag'))  # 锁释放
    return 1


def restart(p_name):
    pid_dict = doc_util.get_a_doc_dict(mark_path + '\\project', 'name')
    kill_pids = {}
    for pname in pid_dict.keys():
        if pname == p_name:
            continue
        else:
            pid = pid_dict[pname]['pid']
            commend = 'taskkill /f /pid ' + pid
            r = os.popen(commend)
            kill_pids[pname] = r.read()
    if len(kill_pids) == 0:
        start()
    for pname in kill_pids:
        pid_dict.pop(pname)
    doc_util.gen_a_doc(mark_path, 'project', pid_dict)
    start()
    return kill_pids


def start():
    commend = 'python main.py'
    os.chdir(base_path)
    r = os.popen(commend)
    return r.read()


def get_pid(param):
    return None


# 关机
def stop(p_name):
    pid_dict = doc_util.get_a_doc_dict(mark_path + '\\project', 'name')
    kill_pids = {}
    for pname in pid_dict.keys():
        if pname == p_name:
            pid = pid_dict[pname]['pid']
            commend = 'taskkill /f /pid ' + pid
            r = os.popen(commend)
            kill_pids[pname] = r.read()


if __name__ == '__main__':
    record_pid('test')
